<template>
  <div>
    <section class="button-box">
      <a-button type="primary" @click="openUserModel()"> 创建用户 </a-button>
    </section>
    <a-table
      :columns="columns"
      :data-source="dataSource"
      :pagination="pagination"
      :loading="loading"
      :row-key="(record) => record.id"
      @change="handleTableChange"
    >
      <template #operation="{ record }">
        <a-button type="link" @click="onUpdate(record)">修改</a-button>
        <a-button type="link" @click="onDelete(record.id)">删除</a-button>
      </template>
    </a-table>

    <a-modal
      v-model:visible="modelState.visible"
      title="创建用户"
      :loading="modelState.modelLoading"
      @ok="handleOk"
    >
      <a-form
        :model="modelState.form"
        :label-col="modelState.labelCol"
        :wrapper-col="modelState.wrapperCol"
      >
        <a-form-item v-for="item in formColumns" :key="item.key" :label="item.title">
          <a-input v-model:value="modelState.form[item.key]" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts">
import { defineComponent, computed, ref, reactive } from '@vue/runtime-core'
import { TableState, TableStateFilters } from 'ant-design-vue/es/table/interface'
import { Table, message as Message } from 'ant-design-vue'
import { usePagination } from 'vue-request'
import cloneDeep from 'lodash/cloneDeep'
import { fetchUserPage, addUser, delUser, updateUser } from '@/api/system/user'
import { User } from '@/model/user'

type Pagination = TableState['pagination']

const columns = [
  {
    title: '登录名',
    dataIndex: 'loginName',
    key: 'loginName',
  },
  {
    title: '昵称',
    dataIndex: 'nickName',
    key: 'nickName',
  },
  {
    title: '密码',
    dataIndex: 'password',
    key: 'password',
  },
  {
    title: '密保邮箱',
    dataIndex: 'protectEmail',
    key: 'protectEmail',
  },
  {
    title: '密保手机号',
    dataIndex: 'protectPhone',
    key: 'protectPhone',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    search: false,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    slots: { customRender: 'operation' },
    search: false,
  },
]

const initUserState = {
  loginName: '',
  nickName: '',
  password: '',
  protectEmail: '',
  protectPhone: '',
}

export default defineComponent({
  name: 'User',
  components: {
    [Table.name]: Table,
  },

  setup() {
    /**
     * table
     */
    const {
      data: dataSource,
      run,
      loading,
      total,
      current,
      pageSize,
    } = usePagination(fetchUserPage, {
      formatResult: (res) => res.records,
      pagination: {
        pageSizeKey: 'size',
      },
    })

    const pagination = computed(() => ({
      total: total.value,
      current: current.value,
      pageSize: pageSize.value,
    }))

    const handleTableChange = (pag: Pagination, filters: TableStateFilters) => {
      run({
        size: pag!.pageSize! || pageSize.value,
        current: pag!.current || current.value,
        ...filters,
      })
    }

    // TODO 搜索
    const formSearch = reactive({})
    /**
     * form
     */
    const modelState = reactive({
      visible: false,
      loading: false,
      form: ref<User>(initUserState),
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
    })
    const formColumns = columns.filter((item) => item.search !== false)

    // 添加用户
    const openUserModel = (data: User) => {
      modelState.form = data || cloneDeep(initUserState)
      modelState.visible = true
    }

    // 弹框确认 新增用户
    const handleOk = () => {
      modelState.loading = true
      const request = modelState.form?.id
        ? updateUser(modelState.form.id, modelState.form)
        : addUser(modelState.form)
      request
        .then(() => {
          Message.success('新增用户成功')
          modelState.visible = false
          handleTableChange({}, formSearch)
        })
        .finally(() => {
          modelState.loading = false
        })
    }

    // 删除用户
    const onDelete = (id: string) => {
      loading.value = true
      delUser(id)
        .then(() => {
          Message.success('删除用户成功')
          handleTableChange({}, {})
        })
        .finally(() => {
          loading.value = false
        })
    }

    // 修改用户
    const onUpdate = (data: User) => {
      const state = cloneDeep(data)
      openUserModel(state)
    }
    return {
      dataSource,
      pagination,
      loading,
      columns,
      handleTableChange,

      openUserModel,
      handleOk,
      formColumns,
      modelState,

      onDelete,
      onUpdate,
    }
  },
})
</script>

<style>
.button-box {
  margin-bottom: 10px;
}
</style>
